var toast = cordova.require('toast');

//nfc -> Filesystem(filename: vI, contents: url) 

var jsonText;
var vPath;
var vPathSent;

//공용 함수
//url encoding
function fEncode(text) {
	//	return encodeURIComponent(text).replace(/'/g,"%27").replace(/"/g,"%22");	
	return encodeURI(text).replace(/'/g, "%27").replace(/"/g, "%22");
}
function fDecode(text) {
	return decodeURIComponent(text.replace(/\+/g, "+"));
}
function fParam(VarSearch) {
	//	var SearchString = window.location.search.substring(1);
	var VariableArray = realQString[1].split('&');
	for (var i = 0; i < VariableArray.length; i++) {
		var KeyValuePair = VariableArray[i].split('=');
		if (KeyValuePair[0] == VarSearch) {
			return KeyValuePair[1];
		}
	}
}

function fParamR(search, target) {
	var VariableArray = target.split('&');
	for (var i = 0; i < VariableArray.length; i++) {
		var KeyValuePair = VariableArray[i].split('=');
		if (KeyValuePair[0] == search) {
			return KeyValuePair[1];
		}
	}
}

function fEmpty() {
	$('#logList').empty();
	$('<li/>').append("기록이 없습니다.").appendTo('#logList');
}

/* 사진 기본값 설정 추가 131209(16:42) */
//로그 목록 출력
function fLoglist(id, name, imgPath, fullPath) {
	var imgUrl;
	window
			.requestFileSystem(
					LocalFileSystem.PERSISTENT,
					0,
					function(imgFileSystem) {
						imgFileSystem.root
								.getFile(
										imgPath,
										{
											create : false
										},
										function() {
											//alert('fullPath : ' + fullPath);
											imgUrl = fullPath
													.substr(
															0,
															fullPath
																	.lastIndexOf(
																			'/',
																			fullPath
																					.lastIndexOf('/')))
													+ '/img/' + id + '.jpg';
											//alert('fixed imgUrl :' + imgUrl);
											$('<li/>')
													.attr('data-role',
															'list-divider')
													.html(
															"<a href='mylog.html?i="
																	+ id
																	+ "'>"//rel='external'
																	+ "<img id='image' style='display:block;width:50px;height:50px;' src='"
																	+ imgUrl
																	+ "' align='left'/>"
																	+ "<h2>"
																	+ name
																	+ "</h2><p>별명</p>")
													.appendTo('#logList');

										},
										function() {
											//alert('failure : ' + imgPath);
											imgUrl = 'ic_launcher.png';

											$('<li/>')
													.attr('data-role',
															'list-divider')
													.html(
															"<a href='mylog.html?i="
																	+ id
																	+ "'>"//rel='external'
																	+ "<img id='image' style='display:block;width:50px;height:50px;' src='"
																	+ imgUrl
																	+ "' align='left'/>"
																	+ "<h2>"
																	+ name
																	+ "</h2><p>별명</p>")
													.appendTo('#logList');
										});
					}, imgError(1));

	function imgError(number) {
		//alert(number + '] error');
	}
}

/* 사진 소스 선택(가져오기, 새로찍기) */
function SrcSlt() {
	navigator.notification.confirm("사진을 어디서 가져올까요?", function(btnNo) {
		if (btnNo == 1) {
			LoadPic();
		} else if (btnNo == 2) {
			capture();
		}
	}, "사진 선택", "사진첩,새로찍기");
}

function capture() {
	// Retrieve image file location from specified source
	navigator.camera.getPicture(getImageURI, function(message) {
		alert('Image Capture Failed');
	}, {
		quality : 100,
		destinationType : Camera.DestinationType.FILE_URI
	});
}

function LoadPic() {
	// Retrieve image file location from specified source
	navigator.camera.getPicture(getImageURI, function(message) {
		alert('Image Capture Failed');
	}, {
		quality : 100,
		destinationType : navigator.camera.DestinationType.FILE_URI,
		sourceType : navigator.camera.PictureSourceType.SAVEDPHOTOALBUM
	});
}

//file system fail 
function fsFail(error) {
	alert("failed with error code: " + error.code);
}

function getImageURI(imageURI) {
	var gotFileEntry = function(fileEntry) {
		var PicAddress = "/AAA/img/" + $('#hash').val() + ".jpg"; //hash값으로 변경
		alert("got image file entry: " + fileEntry.fullPath);
		var gotFileSystem = function(fileSystem) {
			// copy the file 
			fileEntry.copyTo(fileSystem.root, PicAddress, null, null);
		};
		// get file system to copy or move image file to 
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem,
				fsFail);
	};
	//resolve file system for image  
	window.resolveLocalFileSystemURI(imageURI, gotFileEntry, fsFail);
	var image = document.getElementById('image');
	image.style.display = 'block';
	image.src = imageURI;
}
/* 사진 함수 종료 */

/* Google Shortener 시작 */
function fShortUrl(longUrlLink) {
	//	    $("#shortUrlInfo").html("<img src='img/loading.gif'/>");
	//	    var longUrlLink = $("#longUrl").val();
	jQuery.urlShortener({
		longUrl : longUrlLink,
		success : function(shortUrl) {
			//	            $("#shortUrlInfo").html(shortUrl);
			//	        	vUrl = shortUrl;
			alert('단축 성공 : ' + shortUrl);
			return shortUrl;
		},
		error : function(err) {
			//	        	$("#shortUrlInfo").html(JSON.stringify(err));
			alert(JSON.stringify(err));
		}
	});
};
/* Google Shortener 끝 */

var vUrl, vI; //전역 선언
/* SB @131209 추가 */

/* writeFile 함수 */
function fLogWrite(url) {
	console.log("checkpoint 1");
	vUrl = url;
	//	alert('받은 주소 :  ' +vUrl);
	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess,
			onFSError);
}
/*            (function(){ 
 console.log("checkpoint 1"); 
 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onFSError); 
 })(); */

function onFSSuccess(fileSystem) {
	//  console.log('where is the file? ' + fileSystem.root.name); 
	console.log("checkpoint 2");
	/* 저장할 파일 디렉토리 지정(/root/AAA) */
	window.FS = fileSystem;
	var printDirPath = function(entry) {
		console.log("Dir path - " + entry.fullPath);
	};
	// nested directory creation
	createDirectory("AAA/img", printDirPath);
	// fileSystem.root.getDirectory("AAA", {create:true, exclusive:false}, gotFSDir, onFSError); 
}
function createDirectory(path, source) {
	var dirs = path.split("/").reverse();
	var root = window.FS.root;

	var createDir = function(dirs) {
		console.log("create dir " + dirs);
		root.getDirectory(dirs, {
			create : true,
			exclusive : false
		}, gotFSDir, onFSError);
	};
	function gotFSDir(dirEntry) {
		console.log("checkpoint 3 : dir created " + dirEntry.fullPath);
		root = dirEntry;
		if (dirs.length > 0) {
			createDir(dirs.pop());
		} else {
			console.log("all dir created");
			success(dirEntry);
		}
		vI = vUrl.substr(vUrl.indexOf("=") + 1, 13); // ID값 13자리 추출);
		/* 저장할 파일 이름 지정(NFC ID값으로 대체) */
		dirEntry.getFile(vI + '.txt', {
			create : true,
			exclusive : true
		}, gotFileEntry, onFSError);
	}
	function gotFileEntry(fileEntry) {
		console.log("checkpoint 4");
		fileEntry.createWriter(gotFileWriter, onFSError);
	}
	function gotFileWriter(writer) {
		writer.onwrite = function(evt) {
			console.log("checkpoint 5: write Success!");
			alert("저장 성공");
		};
		/* 저장할 데이터(NFC에 저장된 문자열로 대체)! */
		writer.write(vUrl + '\n');
	}
	createDir(dirs.pop());
}
function onFSError(err) {
	console.log(err.code);
}
/* WRITE 함수 끝 */

//개별 목록 출력
function fView(content, imgPath, fullPath) {
	var qString = content[0].split('?')[1];
	var vID = fParamR('i', qString);

	var lat = [];
	var lng = [];

	for (var i = 1; i < content.length - 1; i++) {
		var arData = content[i].split(',');
		lat[i - 1] = Number(arData[0]);
		lng[i - 1] = Number(arData[1]);
	}
	jsonText = JSON.stringify(content.slice(1));


	// map & marker clusters & auto-center //
	
	
	var latlng = new google.maps.LatLng(lat[content.length - 3],
			lng[content.length - 3]); // 맨 뒷줄 등 content.length-3

	var center;
	if (content.slice(1) == "") {
		center = new google.maps.LatLng(37.56647, 126.977963);
	} else {
		center = latlng;
	}

	var options = {
		'zoom' : 15,
		'maxZoom' : 18, // 최대 줌레벨 제한
		'center' : center,
		'mapTypeId' : google.maps.MapTypeId.ROADMAP
	};

	var map = new google.maps.Map(document.getElementById("map_cvs"), options);
	var bounds = new google.maps.LatLngBounds();
	
	/////////////////////to set search box/////////////////
	
	  var defaultBounds = new google.maps.LatLngBounds(
		      new google.maps.LatLng(37.567287,126.974164),
		      new google.maps.LatLng(37.56414,126.982318));
		  map.fitBounds(defaultBounds);

		  // Create the search box and link it to the UI element.
		  var input = /** @type {HTMLInputElement} */(
		      document.getElementById('pac-input'));
		  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

		  var searchBox = new google.maps.places.SearchBox(
		    /** @type {HTMLInputElement} */(input));

		  // Listen for the event fired when the user selects an item from the
		  // pick list. Retrieve the matching places for that item.
		  google.maps.event.addListener(searchBox, 'places_changed', function() {
		    var places = searchBox.getPlaces();

		    for (var i = 0, marker; marker = markers[i]; i++) {
		      marker.setMap(null);
		    }

		    // For each place, get the icon, place name, and location.
		    markers = [];
		    var bounds = new google.maps.LatLngBounds();
		    for (var i = 0, place; place = places[i]; i++) {
		      var image = {
		        url: place.icon,
		        size: new google.maps.Size(71, 71),
		        origin: new google.maps.Point(0, 0),
		        anchor: new google.maps.Point(17, 34),
		        scaledSize: new google.maps.Size(25, 25)
		      };

		      // Create a marker for each place.
		      var marker = new google.maps.Marker({
		        map: map,
		        icon: image,
		        title: place.name,
		        position: place.geometry.location
		      });

		      markers.push(marker);

		      bounds.extend(place.geometry.location);
		    }
		    map.setZoom(19);
		    map.fitBounds(bounds);
		  });
	/////////////////////////////////////////end of search///////////////////
	
	
	var markers = [];
	var position;
	if (content.slice(1) == "") {
		position = new google.maps.LatLng(37.56647, 126.977963);
	} else {
		for (var i = 0; i < lat.length; i++) {
			var position = new google.maps.LatLng(lat[i], lng[i]);
			var marker = new google.maps.Marker({
				'position' : position
			});
			markers.push(marker), bounds.extend(position);
		}
		map.fitBounds(bounds);
	};

	var markerCluster = new MarkerClusterer(map, markers);

	// end of map & marker clusters & auto-center //

	//execute polygon creator//////////////////////////////////
	var creator = new PolygonCreator(map);
	//reset poly
	document.getElementById('resetPath').onclick = function() {
		creator.destroy(), creator = null, creator = new PolygonCreator(map);

	};
	//creator.showData(); 로 좌표 얻을 수 있음
	document.getElementById('savePath').onclick = function() {

		// if(null!=creator.showData()){
		vPath = creator.showData().replace(/\)/g, "\",").replace(/\(/g, "\"")
				.replace(/ /g, "");

	/*	vPathSent = '[' + vPath + '\"\"]';
		$('#g').val(vPathSent);*/

		if ($('#g').val() == "\"\"") {
			vPathSent = '[' + vPath + '\"\"]';
			$('#g').val(vPathSent);
		} else {
			vPathSent = vPath + '\"\"]';
			$('#g').val(jsonText.replace(/\"\"]/,"")+vPathSent);

		//	$('#g').val(jsonText); //map 좌표 textarea로 넘김
		}
		
		//}
	};

	/*			var pathLatLng;
	
	 pathLatLng = creator.showData();
	 alert(pathLatLng);
	 */

	/////////////////////////////////////////////////////

	alert(jsonText);
	$('#o').val(fParamR('o', qString));
	$('#n').val(fParamR('n', qString));
	$('#t').val(fParamR('t', qString));
	$('#m').val(fParamR('m', qString));
	$('#c').val(fParamR('c', qString));
	$('#n').val(fParamR('n', qString));
	$('#d').val(fParamR('d', qString));
	$('#o').val(fParamR('o', qString));
	$('#t').val(fParamR('t', qString));
	$('#m').val(fParamR('m', qString));
	$('#c').val(fParamR('c', qString));
	jsonText = JSON.stringify(content.slice(1)); //좌표값 json으로 변환

	if ($('#g').val() == "\"\"") {
		$('#g').val(vPathSent);
	} else {
		$('#g').val(jsonText); //map 좌표 textarea로 넘김
	}
	;

	var imgUrl;
	//$('#g').val(jsonText); //map

	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(
			imgFileSystem) {
		imgFileSystem.root.getFile(imgPath, {
			create : false
		}, function() {
			//alert('fullPath : ' + fullPath);
			imgUrl = fullPath.substr(0, fullPath.lastIndexOf('/', fullPath
					.lastIndexOf('/')))
					+ '/img/' + vID + '.jpg';
			//alert('fixed imgUrl :' + imgUrl);
			$("#img").append(
					"<img align='top' style='display:block; width:290px; height:210px;' src='"
							+ imgUrl + "'/>");
		}, function() {
			imgUrl = 'ic_launcher.png';
			$("#img").append(
					"<img align='top' style='display:block; width:290px; height:210px;' src='"
							+ imgUrl + "'/>");
		});
	}, imgError);
	function imgError(number) {
		//    	alert('등록된 사진이 없습니다. :' + number);
	}
}

/* 131203(09:35) 추가됨(YMH) */
function fWrite(text, pid) {

	/* writeFile 함수 */
	(function() {
		console.log("checkpoint 1");
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess,
				onFSError);
	})();

	function onFSSuccess(fileSystem) {
		//              console.log('where is the file? ' + fileSystem.root.name); 
		console.log("checkpoint 2");

		/* 저장할 파일 디렉토리 지정(/root/AAA) */
		fileSystem.root.getDirectory("AAA", {
			create : true,
			exclusive : false
		}, gotFSDir, onFSError);
	}

	function gotFSDir(dirEntry) {
		console.log("checkpoint 3");

		/* 저장할 파일 이름 지정(NFC ID값으로 대체) */
		dirEntry.getFile(pid + '.txt', {
			create : false,
			exclusive : true
		}, gotFileEntry, onFSError);
	}

	function gotFileEntry(fileEntry) {
		console.log("checkpoint 4");
		fileEntry.createWriter(gotFileWriter, onFSError);
	}

	function gotFileWriter(writer) {
		writer.onwrite = function(evt) {
			console.log("checkpoint 5: write Success!");
			alert("[File] GPS기록 성공");
		};
		/*이어 쓰기*/
		writer.seek(writer.length);
		/* 저장할 데이터(NFC에 저장된 문자열로 대체)! */
		writer.write(text);
	}

	function onFSError(err) {
		console.log(err.code);
	}
	/* WRITE 함수 끝 */
}

/* readFile 함수 */
function fRead(pid) {
	(function() {
		console.log("read checkpoint 1");
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFRSuccess,
				onFRError);
	})();

	function onFRSuccess(fileSystem) {
		console.log("read checkpoint 2");

		/* 불러올 파일 디렉토리 지정 */
		fileSystem.root.getDirectory("AAA", {
			create : true,
			exclusive : false
		}, gotFRDir, onFRError);
	}

	function gotFRDir(dirEntry) {
		console.log("read checkpoint 3");

		/* 폴더 요소 읽어오기 */
		var directoryReader = dirEntry.createReader();

		directoryReader.readEntries(dirSuccess, onFRError);

		function dirSuccess(entries) {
			console.log('list no. :' + entries.length);
			if (entries.length == 0) {
				//폴더가 비어있으면
				alert('저장 기록이 없습니다.');
				fEmpty();
			} else if (pid) {
				//pid값을 넘겨받았다면 해당 파일만 Read
				dirEntry.getFile(pid + '.txt', null, readFileEntry, onFRError);
			} else {
				//아니면 폴더 내 전체 파일 for문으로 로드
				for (var i = 0; i < entries.length; i++) {
					//alert('파일이름: ' + entries[i].name);
					/*    				if(pid+'.txt' == entries[i].name){
					 //        				dirEntry.getFile(pid+'.txt', null, readFileEntry, onFRError);
					 alert('빙고'+pid);
					 }else{
					 // 불러올 파일 이름 지정(NFC ID값으로 대체) 
					 }
					 */dirEntry.getFile(entries[i].name, null, readFileEntry,
							onFRError);
					//alert(entries[i].name);//이름 확인

					function readFileEntry(fileEntry) {
						console.log("read checkpoint 4");
						fileEntry.file(gotFileReader, onFRError);
					}

					function gotFileReader(file) {
						var reader = new FileReader();
						//	    				$('<li/>').text(file.name).appendTo($('#logList'));

						reader.onloadend = function(content) {
							console.log("read checkpoint 5 : read Success!");
							//    						alert(content.target.result); //파일 내용 전체
							var vArray = fDecode(content.target.result).split(
									'\n');
							var qString = vArray[0].split('?');
							var vID = fParamR('i', qString[1]);
							var vName = fParamR('n', qString[1]);
							var fullPath = file.fullPath;
							var imgPath = 'AAA/img/'
									+ fullPath.substr(
											fullPath.lastIndexOf('/', fullPath
													.lastIndexOf('/'))).split(
											'.')[0] + '.jpg';

							if (pid) {
								fView(vArray, imgPath, fullPath);
							} else {
								fLoglist(vID, vName, imgPath, fullPath);
							}
							//불러온 파일이 출력됨(불러온 파일로 수행할 다음 작업 작성)
						};
						reader.readAsText(file);
					}
				}//for loop end
			}//else end
		}
	}
	function onFRError(error) {
		alert('파일 읽기 에러 : ' + error.code);
	}

}

/* 로그 개별 삭제 fRemove */
/* 131209 삭제 컨펌 추가됨*/
function fRemove(pid) {
	alert('지울항목 :' + pid);
	var targetFile = pid + '.txt';

	/* removeFile 함수 */
	(function removeFile() {
		console.log(">>>>>>remove checkpoint 1");
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRVSuccess,
				onRVError);
	})();

	function onRVSuccess(fileSystem) {
		console.log(">>>>>remove checkpoint 2");

		// 불러올 파일 디렉토리 지정 .
		fileSystem.root.getDirectory("AAA", {
			create : false,
			exclusive : false
		}, gotRVDir, onRVError);
	}

	function gotRVDir(dirEntry) {
		console.log(">>>>>remove checkpoint 3");

		/* 폴더 요소 읽어오기 */
		var directoryReader = dirEntry.createReader();

		directoryReader.readEntries(dirSuccess, onRVError);
		// 불러올 파일 이름 지정 
		//dirEntry.getFile("nfcTest.txt", {create: false, exclusive: false}, gotRVFileEntry, onRVError);

		function dirSuccess(entries) {
			console.log(">>>>>remove checkpoint 4");
			// 불러올 파일 이름 지정(NFC ID값으로 대체)
			console.log(">>>>>>>>>>>>" + entries);

			navigator.notification.confirm("정말 삭제하나요?", // message
			function(button) {
				if (button == 1) {
					dirEntry.getFile(targetFile, null, function(fileEntry) {
						fileEntry.remove(success, onRVError);
					}, onRVError);
				} else if (button == 2) {
					alert("삭제취소");
				}
			}, '삭제확인', '삭제, 취소');
		}

	}

	function success(entry) {
		console.log(">>>>>remove checkpoint 5: Removal succeeded");
		$('#logList').listview("refresh");
		alert("Removal succeeded");
		window.location.replace('#log');
	}

	function onRVError(error) {
		console.log("Error removing file: " + error.code);
	}

};
/* fRemove 끝 */

